#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <unistd.h>  
#include <arpa/inet.h>       
#include <time.h>
#include <pthread.h>

#include "tcp_server.h"
#include "process.h"
#include "common.h"
#include "massege.h"
#include "bus_socket.h"

int process(int nsockfd, struct sockaddr_in *client)
{
	int is_send_bus_info = 0;
	pthread_t  thread;
	ARG *arg = NULL; 

	arg = malloc(sizeof(ARG));
	memset(arg,0,sizeof(ARG));
    arg->connfd = nsockfd;  
    memcpy(&(arg->client), client, sizeof(struct sockaddr_in)); 

	reset_time_out();

	//receive client data
	if (pthread_create(&thread, NULL, start_receive, (void*)arg)) 
	{
        perror("Pthread_create() error");  
        exit(1);  
    } 
	
	while(1)
	{ 
		//check time out
		sleep(1);
		time_out_eclipse();
		if(is_time_out())
		{
			printf("Connect lost %s \n",inet_ntoa(client->sin_addr));			
			pthread_cancel(thread);  
			close(nsockfd);
			exit(-1);			
		}

		//simulate bus info
		is_send_bus_info ++;
		if(is_send_bus_info%6 == 0)
		{
			send_bus_line_info(nsockfd);
			sleep(1);
			send_heart(nsockfd);
			sleep(1);
		}
		if(is_send_bus_info%13 == 0)
		{
			sleep(1);
			send_ask_pic(nsockfd);
			sleep(1);
		}
		/*
		//force client to re-connect
		if(is_send_bus_info%49 == 0)
		{
			printf("Force client %s to re-connect.\n",inet_ntoa(client->sin_addr));
			close(nsockfd);
		}
		*/
				
		if(is_send_bus_info>10000)
		{
			is_send_bus_info = 0;
		}
	}

	return -1;
}

